(function() {
  let TOUCHSTART, TOUCHMOVE, TOUCHEND;
  if(typeof(window.ontouchstart) != 'undefined') {
    TOUCHSTART = 'touchstart';
    TOUCHEND = 'touchend';
    TOUCHMOVE = 'touchmove';

  } else if(typeof(window.onmspointerdown) != 'undefined') {
    TOUCHSTART = 'MSPointerDown';
    TOUCHEND = 'MSPointerUp';
    TOUCHMOVE = 'MSPointerMove';
  } else {
    TOUCHSTART = 'mousedown';
    TOUCHEND = 'mouseup';
    TOUCHMOVE = 'mousemove';
  }

  function tap(node) {
    var x,y;
    window.tap_moving = false;
    node.oncontextmenu = function() {
      return false;
    }
    node.addEventListener(TOUCHSTART, function(e) {
      // console.log("start");
      // document.activeElement.blur();
      x = e.touches[0].pageX;
      y = e.touches[0].pageY;
      window.tap_moving = false;
    });

    node.addEventListener(TOUCHMOVE, function(e) {
      var cur_x = e.changedTouches[0].pageX;
      var cur_y = e.changedTouches[0].pageY;
      // console.log("move",Math.abs(cur_x - x), Math.abs(cur_y - y));
      if(Math.abs(cur_x - x) > 3 || Math.abs(cur_y - y) > 3) {
        window.tap_moving = true;
      }
    });

    node.addEventListener(TOUCHEND, function(e) {
      // console.log("end");
      if(window.tap_moving){
        return;
      }
      if(e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA"){
        document.activeElement.blur();
      }
      e.target.dispatchEvent(new MouseEvent('tap', {
        // isTrusted:true,
        // cancelBubble:false,
        cancelable:true,
        bubbles:true,
        composed:true,
        detail: e
      }));
    });
  }

  tap(document);
})();
